
import React, { PureComponent, Fragment } from 'react';
import { Tree,Modal, message } from 'antd';
import { connect } from 'dva';
import { formatMessage, FormattedMessage } from 'umi/locale';
const { TreeNode } = Tree;

// const treeData = [{
//   title: '0-0',
//   key: '0-0',
//   routes: [{
//     title: '0-0-2',
//     key: '0-0-2',
//   }, {
//       title: '0-0-3',
//       key: '0-0-3',
//     }],
// }, {
//     title: '0-1',
//     key: '0-1',
//     routes: [{
//       title: '0-1-2',
//       key: '0-1-2',
//     }, {
//       title: '0-1-3',
//       key: '0-1-3',
//     }],
//   }];
@connect(({menu}) => ({
  data: menu.routerData,
}))
class AssignPermission extends PureComponent{

  //组件初始化时不调用，组件接受新的props时调用。
  componentWillReceiveProps(nextProps){
    //console.log('11111' + nextProps.permissions)
    this.setState({ checkedKeys: nextProps.permissions});

  }


  state = {
    expandedKeys: [],
    autoExpandParent: true,
    checkedKeys: [],
    selectedKeys: [],
    visible: false,

  }

  showModal = () => {
    //console.log('showModal' + this.props.permissions)
    this.setState({ visible: true });
  }

  handleCancle = () => {
    this.setState({ visible: false });
  }

  handleOk = () => {
    //console.log(this.state.params)
    const {dispatch,record} = this.props;
    dispatch({
      type: 'role/saveNewPermissionsByRoleId',
      payload:{
        newPermissions: this.state.checkedKeys,
        id: record.id
      }
    })
    message.success('权限分配成功，请重新登录');
    this.setState({ visible: false });
  }

  //展开/收起时  获得展开的节点
  onExpand = (expandedKeys) => {
    console.log('onExpand', expandedKeys);
    // if not set autoExpandParent to false, if children expanded, parent can not collapse.
    // or, you can remove all expanded children keys.
    this.setState({
      expandedKeys,
      autoExpandParent: false,
    });
  }
  //点击复选框
  onCheck = (checkedKeys,e) => {
    console.log('onCheck', checkedKeys);
    //console.log('e', [...e.halfCheckedKeys, ...checkedKeys])//数组合并去重
    this.setState({ checkedKeys});
  }
  //点击树节点
  onSelect = (selectedKeys, info) => {
    console.log('onSelect', info);
    console.log('selectedKeys', selectedKeys)
    this.setState({ selectedKeys });
  }

  renderTreeNodes = data => data.map((item) => {

    if (item.routes) {
      //去除数组的最后一个空对象
      const r = item.routes.slice(0,item.routes.length-1);
      return (
        <TreeNode title={formatMessage({ id:`menu.${item.name}`})} key={item.key} dataRef={item}>
          {this.renderTreeNodes(r)}
        </TreeNode>
      );
    }
    return <TreeNode title={formatMessage({ id: `menu.${item.name}` })} key={item.key}  />;
  })

  render() {

    const { data, children, permissions} = this.props;

    // console.log(permissions)
    //console.log(this.state.checkedKeys)
    //去除多余
    const menuData = data.slice(1,data.length-1);
    //console.log(menuData)
    return (
      <Fragment>
        <span onClick={this.showModal}>
          {children}
        </span>
        <Modal
          title="分配权限"
          visible={this.state.visible}
          onOk={this.handleOk}
          onCancel={this.handleCancle}
        >
          <Tree
            defaultExpandAll = {true}
            checkable //节点前添加 Checkbox 复选框
            onExpand={this.onExpand} //展开/收起节点时触发
            expandedKeys={this.state.expandedKeys} //受控）展开指定的树节点
            autoExpandParent={this.state.autoExpandParent} //是否自动展开父节点
            onCheck={this.onCheck} //点击复选框触发
            checkedKeys={this.state.checkedKeys} //（受控）选中复选框的树节点
            onSelect={this.onSelect} //点击树节点触发
            selectedKeys={this.state.selectedKeys} //受控）设置选中的树节点
          >
            {this.renderTreeNodes(menuData)}
          </Tree>
        </Modal>
      </Fragment>
    );
  }
}

export default AssignPermission;
